﻿using NetCore.IBLL;
using ServiceStack.Redis;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace NetCore.RedisCache
{
    /// <summary>
    /// Redis缓存服务
    /// </summary>
    public class CacheService : ICache
    {
        private readonly string HOST ;

        public CacheService()
        {
            HOST = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables().Build().GetSection("AppConfiguration").GetValue<string>("RedisHost");
        }

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.Get<T>(key);
            }
        }
        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IList<T> GetList<T>(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.Get<List<T>>(key);
            }
        }
        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="key"></param>
        public void Remove(string key)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Del(key);
            }
        }
        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public void Set<T>(string key, T data)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Set<T>(key, data);
            }
        }

        /// <summary>
        /// 写入缓存定时清除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="timeout"></param>
        public void Set<T>(string key, T data, int timeout)
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                client.Set<T>(key, data);
            }
        }

        /// <summary>
        /// 获取所有键集合
        /// </summary>
        /// <returns></returns>
        public List<string> Keys()
        {
            using (RedisClient client = new RedisClient(HOST))
            {
                return client.SearchKeys("*");
            }
        }
    }
}
